const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')

const Image = mongoose.model('Image')

router.get('/', async (ctx, next) => {
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const stats = await statsfn()
  await ctx.render('index', {
    title: '图片分享',
    images, stats, username: ctx.session.username
  })
})

router.get('/login', async ctx => {
  await ctx.render('login', {})
})

router.post('/login', async ctx => {
  const {username, password} = ctx.request.body
  if(username === 'tom' && password === '123') {
    ctx.session.username = username
  }
  ctx.redirect('/')
})

router.get('/logout', async ctx => {
  ctx.session.username = undefined
  ctx.redirect('/')
})
router.get('/login', async cyx => {
  await ctx.render('login')
})
module.exports = router
